package com.zhixi.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName CommonController
 * @Author zhangzhixi
 * @Description 文件的上传和下载
 * @Date 2022-7-11 10:56
 * @Version 1.0
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    /**
     * 文件上传的路径
     */
    private static final String BASE_PATH;

    static {
        BASE_PATH = System.getProperty("user.dir") +
                File.separatorChar +
                "src" +
                File.separatorChar +
                "main" +
                File.separatorChar +
                "resources" +
                File.separatorChar +
                "static" +
                File.separatorChar +
                "images" +
                File.separatorChar;
        log.info("文件上传的路径：{}", BASE_PATH);
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 已上传的文件名
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件删除
        log.info(file.toString());

        //获取原始的文件名
        String originalFilename = file.getOriginalFilename();
        //获取上传的文件后缀
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用uuid重新生成文件名，防止文件名重复造成文件覆盖
        String fileName = UUID.randomUUID() + suffix;

        try {
            //将临时文件存储到指定位置
            file.transferTo(new File(BASE_PATH + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {
        FileInputStream fis = new FileInputStream(BASE_PATH + fileName);
        ServletOutputStream fos = response.getOutputStream();
        // 获取响应
        response.setContentType("application/octet-stream");
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 写出
        try {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                fos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
